<?php
namespace app\common\logic;

use app\common\exception\FailException;
use app\common\model\AgentLog;
use think\Controller;

class Agent extends Controller
{
   function get_team($id){

       $userteam_levelone=\app\common\model\User::alias('u')
           ->join('t_capital c','u.id = c.uid','LEFT')->where("u.top_agent_id",$id)->where("u.agent_id",0)->where("u.is_agent",0)->field("u.id,u.agent_name,u.username,u.is_agent,c.count_agent_money")->select();
       $userteam_leveltwo=\app\common\model\User::alias('u')
           ->join('t_capital c','u.id = c.uid','LEFT')->where("u.top_agent_id",$id)->where("u.agent_id",0)->where("u.is_agent",1)->field("u.id,u.agent_name,u.username,u.is_agent,c.count_agent_money")->select();


       return ['huiyuan'=>$userteam_levelone,"daili"=>$userteam_leveltwo];
   }


    function team_info($id){

        $userteam_leveltwo=\app\common\model\User::alias('u')
            ->join('t_capital c','u.id = c.uid','LEFT')->where("u.id",$id)->where("u.agent_id",0)->where("u.is_agent",1)->field("u.id,u.agent_name,u.username,u.mobile,u.agent_bl,c.count_agent_money")->find();

        if(!$userteam_leveltwo){
           throw new FailException(["code"=>201,"msg"=>"该账户已经不是代理了","errorCode"=>433]);
        }
        return $userteam_leveltwo;
    }
  
     function team_info2($id){

        $userteam_leveltwo=\app\common\model\User::alias('u')
            ->join('t_capital c','u.id = c.uid','LEFT')->where("u.id",$id)->where("u.agent_id",0)->where("u.is_agent",0)->field("u.id,u.agent_name,u.username,u.mobile,u.agent_bl,c.count_agent_money")->find();

        if(!$userteam_leveltwo){
           throw new FailException(["code"=>201,"msg"=>"该账户已经不是代理了","errorCode"=>433]);
        }
        return $userteam_leveltwo;
    }

   function agent_center($uid){
      return \app\common\model\Agent::where("id",$uid)->find();
   }

   function get_agent_log($id,$page,$num,$start_time,$end_time){

       $where=[];
       if($start_time){
           $where['addtime']=['egt',$start_time];
       }

       if($end_time){
           $where['addtime']=['elt',$end_time];
       }
       if($start_time&&$end_time){
           $where['addtime']=['between',[$start_time,$end_time]];
       }
       $data =  AgentLog::where("aid",$id)->where($where)->page($page,$num)->select();
       $totle=  AgentLog::where("aid",$id)->where($where)->sum("money");
       return [$data,$totle];
   }

   function set_agent($userid,$uid,$status,$agent_bl,$agent_name){
       $agent_user=\app\common\model\User::where("top_agent_id",$userid)->where("id",$uid)->find();
       if(!$agent_user){
           throw new FailException(["code"=>201,"msg"=>"你无权修改该二级代理商","errorCode"=>404]);
       }

       $ret= \app\common\model\User::where("top_agent_id",$userid)->where("id",$uid)->update([
           "is_agent"=>$status,
           "agent_bl"=>$agent_bl,
           "agent_name"=>$agent_name
       ]);

       return $ret;
   }
}